package ext.tianma.part.util.emailService;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;

import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.util.GetSuperior;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.workflow.WorkflowUtil;
import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.mail.EMailMessage;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;

/**
 * 用于工作流节点任务催办,定期执行,邮件通知
 * 
 * @author laichao_sun
 *
 */

public class HastenWorkEmail {
	private static String codebase = "";
	private static final String OBSOLESCENCE = "OBSOLESCENCE";
	static {
		try {
			WTProperties wp = WTProperties.getLocalProperties();
			codebase = wp.getProperty("wt.server.codebase");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	// 查询获取存在的工作流
	public static void getWorkflow() {
		try {
			PropertiesUtil ut = new PropertiesUtil(configFilePath);
			// 工作流进程的名字
			String WorkflowName = ut.getValueByKey("Workflow.name");
			String[] name = "".equals(WorkflowName) || WorkflowName == null ? null : WorkflowName.split(";");// 2、why？
			if (!(name == null)) {
				for (int i = 0; i < name.length; i++) {
					String processTemplateName = name[i];
					
					String nodes = ut.getValueByKey(processTemplateName + ".节点");
					
					String types = ut.getValueByKey("对象.类型");
				
					if (StringUtil.isNullOrEmpty(nodes)) {
						continue;
					}

					// 根据工作流模板,运行状态,获取所有存在的工作流程
					QueryResult enuHistoryProcess = getProcess(processTemplateName);
					if (enuHistoryProcess == null) {
						continue;
					} else {
						while (enuHistoryProcess.hasMoreElements()) {
							WfProcess historyProcess = (WfProcess) enuHistoryProcess.nextElement();
							// 获取流程中正在进行的任务节点
							SendEmail(historyProcess, nodes, types);
						}
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对当前流程进行处理邮件通知
	 * 
	 * @param historyProcess
	 */
	private static void SendEmail(WfProcess historyProcess, String nodes, String types) {
		try {
			// 获取流程正在运行的流程任务节点
			QueryResult activityNode = getActiveAssignedActivity(historyProcess);
			if (!(activityNode == null)) {
				while (activityNode.hasMoreElements()) {
					WfAssignedActivity activity = (WfAssignedActivity) activityNode.nextElement();
					if (nodes.contains(activity.getName())) {
						

						// 获取正在进行流程的用户
						QueryResult allWorkItems;
						allWorkItems = WorkflowUtil.getWorkItemByParent(activity);
						while (allWorkItems.hasMoreElements()) {
							WorkItem workItem = (WorkItem) allWorkItems.nextElement();
							String status = workItem.getStatus().getDisplay(Locale.CHINA);
							String completeName = workItem.getCompletedBy();
							if (StringUtil.isNullOrEmpty(completeName) && (!"已完成".equals(status))) {
								// 任务所有人
								
								WTPrincipalReference user = workItem.getOwnership().getOwner();
								String userName = workItem.getOwnership().getOwner().getName();
								String Email = workItem.getOwnership().getOwner().getEMail();
							
								if (StringUtil.isNullOrEmpty(Email)) {
									continue;
								}
								// 获取流程的主对象
								WTObject obj = getPBO(historyProcess);
								if (obj instanceof WTDocument) {
									WTDocument doc = (WTDocument) obj;
									String docType = ClientTypedUtility.getLocalizedTypeName(doc, Locale.CHINA);
							
									if (types.contains(docType)) {
										boolean flag = TemporaryEmail(activity,doc,Email,user,userName);//临时图纸任务
										if(!flag) {
											// 任务详细信息url
											String object_ref = (new wt.fc.ReferenceFactory()).getReferenceString(workItem);
											String url = codebase + "/app/#ptc1/tcomp/infoPage?oid=" + object_ref;
											String content = getContent(doc,url,userName);
											sendEmail(user,Email, "【催办任务】图纸审核", content);
										}
									
									}
								} else if (obj instanceof WTPart) {
									WTPart part = (WTPart) obj;
									String partType = ClientTypedUtility.getLocalizedTypeName(part, Locale.CHINA);
								
									if (types.contains(partType)) {
										// 任务详细信息url
										String object_ref = (new wt.fc.ReferenceFactory()).getReferenceString(workItem);
										String url = codebase + "/app/#ptc1/tcomp/infoPage?oid=" + object_ref;
										String content = getContent(part,url,userName);
										sendEmail(user,Email, "【催办任务】 部件审核", content);
									
									}
								}
							}

						}

					}
				}
			}
		} catch (Exception e) {

		}
	}
	/**
	 * 临时图纸转正式图纸任务催办,
	 * @param activity 
	 * @param doc
	 * @param email 
	 * @param user 
	 * @param userName 
	 * @return
	 */
	private static boolean TemporaryEmail(WfAssignedActivity activity, WTDocument doc, String email, WTPrincipalReference user, String userName) {
		try {
			String name  = activity.getName();
			if("临时图纸提交".equals(name)) {
				//图纸有效期
				String PDFValidity = IbaAttributeUtil.getAttributeValue(doc, "PDFValidity");
				if("长期有效".equals(PDFValidity)) {
					return false;
				}else {
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					//当前时间	
					Date nowDate = new Date();
					//图纸有效期
					Date endDate = simpleDateFormat.parse(PDFValidity);
					if(nowDate.after(endDate)) {
						PDFValidity = PDFValidity+"-过期废弃";
						Hashtable<String, String> values = new Hashtable<String, String>();
						values = addToHashtable(values, "PDFValidity", PDFValidity);
						IBAUtil.setSoftTypeIBAValues(doc, values);
						WfEngineHelper.service.terminateObjectsRunningWorkflows(doc);
						State state = State.toState(OBSOLESCENCE);
						LifeCycleHelper.service.setLifeCycleState(doc, state);
						return true;
					}
					//图纸有效期 前7天
					Calendar ct = Calendar.getInstance();
					ct.setTime(simpleDateFormat.parse(PDFValidity));
					ct.add(Calendar.SECOND, -7*24*3600);;// 设置天
					String date = simpleDateFormat.format(ct.getTime());
					Date endDate2 = simpleDateFormat.parse(date);
					if(nowDate.after(endDate2)) {
						// 创建者的上一级主管
						String name2 = GetSuperior.getSuperior(name);
						System.out.println("上级领导的名字:" + name2);
						WTUser user2 = getUserByName(name2);
						if(user2 !=null) {
							String emailAddr2 = user2.getEMail();// 电子邮件
							email = email+";"+emailAddr2+";";
						}
					}
					
					String content = "<div style=\"width: 780px;padding: 15px;margin: 20px auto;border: 2px solid #33CCFF;border-top-width: 8px;text-align:left;\"><h2>PLM任务催办</h2><hr><div id=\"main-content\"><p>"+userName+"</p><p>你好，PLM提醒你：<br>PLM系统有任务需要完成:"+doc.getNumber()+" 图纸需转正式请尽快完成！<br></p></div></div>"+getfoot();				
					sendEmail(user,email,"【催办任务】临时图纸转正式",content);
					return true;
				}

			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 拼接邮件的主要内容
	 * 
	 * @param obj
	 * @param url 
	 * @param userName 
	 * @return
	 */
	private static String getContent(WTObject obj, String url, String userName) {
		String infoPage = "";
		
		String content = "";
		if (obj instanceof WTDocument) {
			WTDocument OBJ = (WTDocument) obj;
			String name = OBJ.getName();
			infoPage = "<a target='_blank' href='" + url + "'>" + name + "</a>";
			content = "<div style=\"width: 780px;padding: 15px;margin: 20px auto;border: 2px solid #33CCFF;border-top-width: 8px;text-align:left;\"><h2>PLM任务催办</h2><hr><div id=\"main-content\"><p>"+userName+"</p><p>你好，PLM提醒你：<br>PLM系统有审核任务需要完成:"+infoPage+" 图纸请尽快签核！<br></p></div></div>"+getfoot();
			return content;
		} else if (obj instanceof WTPart) {
			WTPart OBJ = (WTPart) obj;
			String number = OBJ.getNumber();
			infoPage = "<a target='_blank' href='" + url + "'>" + number + "</a>";
			content = "<div style=\"width: 780px;padding: 15px;margin: 20px auto;border: 2px solid #33CCFF;border-top-width: 8px;text-align:left;\"><h2>PLM任务催办</h2><hr><div id=\"main-content\"><p>"+userName+"</p><p>你好，PLM提醒你：<br>PLM系统有审核任务需要完成:"+infoPage+" 部件请尽快签核！<br></p></div></div>"+getfoot();
			return content;
		}
		return null;
	}
	//获取邮件下面的字段
	public static String getfoot(){
		String foot = "<div class=\"MsoNormal\"align=\"center\"style=\"text-align:center\"><span lang=\"EN-US\"style=\"font-size:12.0pt;font-family:宋体\"><hr size=\"2\"width=\"100%\"align=\"center\"></span></div><p class=\"MsoNormal\"align=\"left\"style=\"text-align:left\"><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">“</span><span lang=\"EN-US\"style=\"font-size:9.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:gray\">This e-mail message together with any attachments thereto(if any)is confidential,intended only for the use of the named recipient(s)above.Any unauthorized review,use,copying,disclosure,or distribution of any information contained in or attached to this transmission is STRICTLY PROHIBITED.If you have received this message in error,or are not the named recipient(s),please immediately notify the sender and delete this e-mail message and any attached documentation from your computer.Thank you!<br></span><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">本电子邮件及附件（如有）所载信息均为保密信息，仅供指定收件人使用。未经授权者收到此信息均无权阅读、使用、复制、揭露或散布。若您误收到本电子邮件或非本电子邮件的指定收件人，请立即通知发件人并从电脑中删除该电子邮件及其附件。谢谢！”</span></p>";
		return foot;
	}

	/**
	 * 用于发送邮件通知
	 * @param user 
	 * 
	 * @param email
	 * @param string
	 */
	private static void sendEmail(WTPrincipalReference user, String Email, String titleStr, String content) {
		try {

			// 测试邮箱内容
			//Email = "laichao_sun@tianma.cn";

			// 邮件内容
			StringBuffer body = new StringBuffer();
			body.append(content);
			String[] emailSendTo = "".equals(Email) || Email == null ? null : Email.split(";");// 2、why？
			EMailMessage email = EMailMessage.newEMailMessage();
			email.setOriginator(user);
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 根据流程获取流程主对象
	 * 
	 * @param wfprocess
	 * @return
	 * @throws WTException
	 */
	private static WTObject getPBO(WfProcess wfprocess) throws WTException {
		WTObject wtobject = null;
		ReferenceFactory referencefactory = new ReferenceFactory();
		WTReference wtreference = wfprocess.getBusinessObjectReference(referencefactory);
		if (wtreference == null && wfprocess.isNested()) {
			wtobject = (WTObject) wfprocess.getContext().getValue("primaryBusinessObject");
		}
		if (wtreference != null && wtreference.getKey() != null) {
			wtobject = (WTObject) wtreference.getObject();
		}
		return wtobject;
	}

	/**
	 * 获取流程正在运行的流程任务节点
	 */
	@SuppressWarnings("deprecation")
	private static QueryResult getActiveAssignedActivity(WfProcess wfprocess) throws WTException {
		QuerySpec querysearch = null;
		QueryResult queryresult = null;
		querysearch = new QuerySpec(WfAssignedActivity.class);
		SearchCondition sc = new SearchCondition(WfAssignedActivity.class, "parentProcessRef.key",
				SearchCondition.EQUAL, getOid(wfprocess));
		querysearch.appendSearchCondition(sc);
		querysearch.appendAnd();
		SearchCondition sc2 = new SearchCondition(WfAssignedActivity.class, WfAssignedActivity.STATE,
				SearchCondition.EQUAL, WfState.OPEN_RUNNING);
		querysearch.appendSearchCondition(sc2);
		queryresult = PersistenceHelper.manager.find(querysearch);
		return queryresult;
	}

	private static ObjectIdentifier getOid(Object obj) {
		if (obj == null) {
			return null;
		}
		if (obj instanceof ObjectReference) {
			return (ObjectIdentifier) ((ObjectReference) obj).getKey();
		} else {
			return PersistenceHelper.getObjectIdentifier((Persistable) obj);
		}
	}

	/**
	 * 根据工作流模板获取所有流程的集合
	 * 
	 * @param template
	 * @return
	 */
	@SuppressWarnings("deprecation")
	private static QueryResult getProcess(String processTemplateName) throws WTException {
		QuerySpec querysearch = null;
		QueryResult queryresult = null;
		querysearch = new QuerySpec(WfProcess.class);
		if (processTemplateName != null && processTemplateName.length() > 0) {
			SearchCondition sc1 = new SearchCondition(WfProcess.class, "name", SearchCondition.LIKE,
					processTemplateName + "_%");
			querysearch.appendWhere(sc1);
			SearchCondition sc2 = new SearchCondition(WfProcess.class, "state", SearchCondition.LIKE,
					WfState.OPEN_RUNNING);
			querysearch.appendAnd();
			querysearch.appendSearchCondition(sc2);
			queryresult = PersistenceHelper.manager.find(querysearch);
			return queryresult;
		}
		return null;
	}
	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}
	/***
	 * 根据用户名称获取user
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 */
	@SuppressWarnings("rawtypes")
	private static WTUser getUserByName(String name) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", name);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}
}
